﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebUI.BL.Helper;

namespace WebUI
{
    public partial class UploadImg : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                LoadImg();
            }
        }

        private void LoadImg()
        {
            var bl = new UploadFileBL();
            GridViewUploadedImageFile.DataSource = bl.GetAllImg();
            GridViewUploadedImageFile.DataBind();
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            string imgName = string.Empty;
            byte[] image = null;
            if(uploadFile.PostedFile!=null &&uploadFile.PostedFile.FileName!="")
            {
                string fileExtension = Path.GetExtension(uploadFile.FileName);
                if(fileExtension==".jpg"||fileExtension==".gif"||fileExtension==".png")
                {
                    imgName = Path.GetFileName(uploadFile.FileName);
                    image=new byte[uploadFile.PostedFile.ContentLength];
                    HttpPostedFile uploadedImg = uploadFile.PostedFile;
                    uploadedImg.InputStream.Read(image, 0, (int) uploadFile.PostedFile.ContentLength);
                    var bl=new UploadFileBL();
                    bl.Insert("insert",imgName,image,"son");
                }
            }
            
            LoadImg();

        }

        protected void GridViewUploadedImageFile_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if(e.Row.RowType==DataControlRowType.DataRow)
            {
                string ImageID = GridViewUploadedImageFile.DataKeys[e.Row.RowIndex].Values[0].ToString();
                System.Web.UI.WebControls.Image uImage = (System.Web.UI.WebControls.Image)e.Row.FindControl("UsrImages");
                uImage.ImageUrl = "DisplayImage.ashx?ImgId=" + ImageID;

                LinkButton btnSelect = e.Row.FindControl("btnSelect") as LinkButton;


                string nameFile = DataBinder.Eval(e.Row.DataItem, "ImageName").ToString();
                btnSelect.Attributes.Add("value", nameFile);
                btnSelect.Attributes.Add("onclick", String.Format("passValue({0},{1})", btnSelect.ClientID, ImageID));
                
         

            }
        }
    }
}